<template>
  <div class="my-music">
    <div class="album-slide">
      <div class="album-img">
        <img :src="sConsumer.avatar"/>
      </div>
      <ul class="album-info">
        <li>昵称：{{ sConsumer.username }}</li>
        <li>性别：{{ +sConsumer.sex === 0 ? '女' : '男' }}</li>
        <li>生日：{{ sConsumer.birth }}</li>
      </ul>
    </div>
    <div class="album-content">
      <div class="album-title">
        个性签名：{{ sConsumer.introduction }}
      </div>
      <div style="margin-top: 15px;margin-bottom: 15px">
        <span>
            <el-button size="mini" type="danger" icon="el-icon-circle-plus-outline" class="ml-5"
                       @click="dialogFormVisible=true">{{ approveStatus }}</el-button>
        </span>
      </div>
      <!--用户上传的乐谱显示-->
      <el-table :data="tableData" stripe style="width: 100%; border-radius:15px;">
        <el-table-column prop="name" label="乐谱名" style="margin-left: 20px;"></el-table-column>
        <el-table-column prop="staff" label="乐谱" align="center" >
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="previewXml(scope.row.file)" >乐谱显示</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="状态">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.type===0">审核通过</el-tag>
            <el-tag type="danger" v-if="scope.row.type===1">未通过</el-tag>
            <el-tag type="info" v-if="scope.row.type===2">待审批</el-tag>
          </template>
        </el-table-column>

        <!--按钮 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button  type="primary" v-if="scope.row.type===1" @click="handleEdit(scope.row)">重新上传
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="padding: 10px 0;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
      <div class="songs-body">
        <album-content :staffsList="collectList">
          <template slot="title">收藏列表</template>
        </album-content>
      </div>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog title="新增" :visible.sync="dialogFormVisible" width="40%">
      <el-form label-width="90px" width="30%" size="mini">
        <el-form-item label="乐谱名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="风格">
          <!--一级分类-->
          <el-select
              v-model="courseInfo.subjectParentId"
              placeholder="一级分类" @change="subjectLevelOneChanged">
            <el-option
                v-for="style in subjectOneList"
                :key="style"
                :label="style"
                :value="style"/>
          </el-select>
          <!-- 二级分类 -->
          <el-select v-model="courseInfo.subjectId" placeholder="请选择">
            <el-option
                v-for="subject in subjectTwoList"
                :key="subject.id"
                :label="subject.title"
                :value="subject.id"/>
          </el-select>
        </el-form-item>
        <!--乐谱文件-->
        <el-form-item label="mxl文件" prop="file">
          <el-upload
              action=""
              :show-file-list="true"
              :multiple="false"
              :auto-upload="false"
              :on-change="handleChange"
              :file-list="fileList"
              accept=".mxl"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传mxl文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <!--头像-->
        <el-form-item label="封面" prop="introduction">
          <el-upload
              action=""
              :show-file-list="true"
              :multiple="false"
              :auto-upload="false"
              :on-change="handlePicture"
              :file-list="pictureList"
              list-type="picture-card"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="uploadStaff" size="mini">确 定</el-button>
      </span>
      </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="40%">
      <el-form label-width="90px" width="30%"  size="mini">
        <el-form-item label="乐谱名" prop="name" >
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="风格">
          <!--一级分类-->
          <el-select
              v-model="form.style"
              placeholder="一级分类" @change="subjectLevelOneChanged">
            <el-option
                v-for="style in subjectOneList"
                :key="style"
                :label="style"
                :value="style"/>
          </el-select>
          <!-- 二级分类 -->
          <el-select v-model="form.title" placeholder="请选择">
            <el-option

                v-for="subject in subjectTwoList"
                :key="subject.id"
                :label="subject.title"
                :value="subject.id"/>
          </el-select>
        </el-form-item>
        <!--乐谱文件-->
        <el-form-item label="mxl文件" prop="file" >
          <el-upload

              action=""
              :show-file-list="true"
              :multiple="false"
              :auto-upload="false"
              :on-change="handleChange"
              :file-list="fileList"
              accept=".mxl"
          >
            <el-button size="small" type="primary" >点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传mxl文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <!--头像-->
        <el-form-item label="封面" prop="picture">
          <el-upload
              action=""
              :show-file-list="true"
              :multiple="false"
              :auto-upload="false"
              :on-change="handlePicture"
              :file-list="pictureList"
              list-type="picture-card"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer" >
        <el-button @click="editVisible = false"  size="mini">取 消</el-button>
        <el-button type="primary" @click="saveEdit"  size="mini">确 定</el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import {mixin} from "@/mixins";
import {mapGetters} from "vuex";
import AlbumContent from '../components/AlbumContent'
import showXml from '../util/showxml'
import {
  getAllStaffStyle,
  getCollectOfStaff,
  returnStaffFile,
  selectUpdateStaffByConsumerId,
  songOfConsumerId,
  StaffListStyleAll,
  uploadStaffFile
} from "@/api";


export default {
  name: "MyStaff",
  mixins: [mixin],
  components: {
    AlbumContent,
  },
  data() {
    return {
      editVisible: false,//默认不展示编辑
      tableData: [],
      total: 0,//分页，默认总数为0
      pageNum: 1,//分页，默认第一页
      pageSize: 3,//分页，默认一页有两条
      isCollection: false,
      username: '',//用户名
      sex: '',//性别
      birth: '',//生日
      introduction: '',//签名
      collection: [],//收藏的乐谱列表
      collectList: [],//收藏的乐谱列表（带歌曲详情）
      form: {
        picture: null,
        name: '',
        introduction: '',
        file: null,
        style:'',
        title:'',
        staffListId: ''
      },
      pictureList: [],
      fileList: [],
      dialogFormVisible: false,//新增
      sConsumer: localStorage.getItem("sConsumer") ? JSON.parse(localStorage.getItem("sConsumer")) : {},//从浏览器里取数据，
      saveBtnDisabled: false, // 保存按钮是否禁用
      courseInfo:{
        subjectId: '',      //二级分类id
        subjectParentId:'', //一级分类id
      },
      subjectOneList:[],  //一级分类
      subjectTwoList:[] ,  //二级分类
    }


  },
  computed: {
    ...mapGetters([
      'listOfStaffs',//当前播放列表
    ]),
    approveStatus() {
      return '上传乐谱'
    }
  },
  mounted() {
    this.getCollection(this.sConsumer.id);
    this.getData()
    this.getAllStaffStyle()
  },
  methods: {
    //查询乐谱
    getData() {
      this.tableData = [];//清空tableData里的数据
      selectUpdateStaffByConsumerId(
          this.pageNum,
          this.pageSize,
          this.sConsumer.id
      ).then(res => {
        const {records, total, pages} = res.data;
        this.tableData.push(...(records||[]));
        this.total = total
        if (this.pageNum > 1 && pages < this.pageNum) {
          console.log('当前页没有数据并且不是第一页是，重新请求前一页的数据')
          this.pageNum--;
          this.getData();
        }
      })
    },

    //操作----编辑
    handleEdit(row) {
      Object.assign(this.form, row) //把数据显示在表单上
      this.editVisible = true//打开弹窗
      console.log('form',this.form)
    },
    //编辑确定按钮
    saveEdit() {

      const params = {...this.form};
      const formData = new FormData();
      Object.entries(params).forEach(([key, value]) => {
        formData.append(key, value)
      })
      returnStaffFile(formData).then(res => {
        if (res) {
          this.$message.success("上传成功")
          this.editVisible = false//关闭弹窗
          this.getData()//刷新数据
        } else {
          this.$message.error("上传失败")
          this.editVisible = false//关闭弹窗
        }
      })
    },
    //分页
    handleSizeChange(pageSize) {
      console.log(`每页 ${pageSize} 条`);
      this.pageSize = pageSize
      this.getData()//调用分页方法
    },
    handleCurrentChange(pageNum) {
      console.log(`当前页: ${pageNum}`);
      this.pageNum = pageNum
      this.getData()//调用分页方法
    },
    previewXml(fileUrl) {
      // // 这里传入不同的url，展示不同滴文件
      showXml(fileUrl)
    },
    //收藏列表根据用户id查询
    getCollection(consumerId) {
      getCollectOfStaff(consumerId).then(res => {
        this.collectList.push(...(res.data || []))
      })
    },
    //上传乐谱
    handleChange(file){
      this.form.file = file.raw;
      this.fileList = [file];
    },
    //上传图片
    handlePicture(picture) {
      this.form.picture = picture.raw;
      this.pictureList = [picture];
    },
    //上传乐谱
    uploadStaff() {
      const params = Object.assign(this.form,{
        consumerId: this.sConsumer.id,
        staffListId:this.courseInfo.subjectId
      })
      const formData = new FormData();
      Object.entries(params).forEach(([key, value]) => {
        formData.append(key, value)
      })
      uploadStaffFile(formData).then(res => {
        this.$message.success(res.message)
        this.dialogFormVisible = false;
        this.getData()
      })
    },

    //点击某个一级分类，会触发change事件，显示对应的二级分类
    subjectLevelOneChanged(value){
      this.goStaffListOfStyleAll(value)
      },
    //查找所有的风格
    getAllStaffStyle(){
      getAllStaffStyle().then(res =>{
        this.subjectOneList.push(...res.data.map(item=>item.style))
      })
    },
    //根据style查询对应的乐谱集
    goStaffListOfStyleAll(style) {
      StaffListStyleAll(style).then(res => {
        this.subjectTwoList.length=0;
        this.courseInfo.subjectId=''; // 已选择的二级菜单清空
        this.subjectTwoList.push(...res.data.map(item=>({
              title:item.title,
              id:item.id
            })
        ))

      })
    },
  }
}
</script>

<style lang="scss" scoped>
@import "../assets/css/my-music.scss";
</style>